package com.barbeque.mall.service.wx;

import com.barbeque.mall.bean.BasePageInfo;
import com.barbeque.mall.bean.advertise.MarketCoupon;
import com.barbeque.mall.bean.advertise.MarketCouponUser;
import com.barbeque.mall.bean.advertise.MarketCouponUserExample;
import com.barbeque.mall.bean.comment.MarketComment;
import com.barbeque.mall.bean.config.MarketSystem;
import com.barbeque.mall.bean.goods.MarketGoodsProduct;
import com.barbeque.mall.bean.goods.MarketGoodsProductExample;
import com.barbeque.mall.bean.order.MarketOrder;
import com.barbeque.mall.bean.order.MarketOrderExample;
import com.barbeque.mall.bean.order.MarketOrderGoods;
import com.barbeque.mall.bean.order.MarketOrderGoodsExample;
import com.barbeque.mall.bean.param.CommonData;
import com.barbeque.mall.bean.user.MarketAddress;
import com.barbeque.mall.bean.user.MarketUser;
import com.barbeque.mall.bean.wx.cart.MarketCart;
import com.barbeque.mall.bean.wx.cart.MarketCartExample;
import com.barbeque.mall.bean.wx.order.*;
import com.barbeque.mall.exception.ProductNumberException;
import com.barbeque.mall.mapper.*;
import com.barbeque.mall.util.ExpressCompany;
import com.barbeque.mall.util.OptionStatus;
import com.barbeque.mall.util.OrderConstant;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @author Tezel
 * @since 2022/07/18 19:56
 */

@Service
@Transactional(rollbackFor = Exception.class)
public class WxOrderServiceImpl implements WxOrderService {

    @Autowired
    MarketAddressMapper addressMapper;

    @Autowired
    MarketCartMapper cartMapper;

    @Autowired
    MarketCouponMapper couponMapper;

    @Autowired
    MarketCouponUserMapper couponUserMapper;

    @Autowired
    MarketOrderMapper orderMapper;

    @Autowired
    MarketOrderGoodsMapper orderGoodsMapper;

    @Autowired
    MarketCommentMapper commentMapper;

    @Autowired
    MarketSystemMapper systemMapper;

    @Autowired
    MarketGoodsProductMapper goodsProductMapper;


    @Override
    public  WxOrderSubmitPo submit(WxOrderCommitBo wxOrderSubmitBo) {
        //等待wx/goods/detail,wx/cart/goodscount,wx/cart/fastadd,wx/cart/checkout
        //从购物车中取出商品，取出之后逻辑删除
        //如果cartId=0，表示是从购物车中选择之后提交，如果cartId!=0，表示是从商品详情页面直接提交，
        //已经判断库存是否足够，此处不赘述
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        //获取当前登录的userId
        Subject subject = SecurityUtils.getSubject();
        PrincipalCollection principals = subject.getPrincipals();
        if (principals == null) {
            subject.logout();
        }
        MarketUser primaryPrincipal = (MarketUser) principals.getPrimaryPrincipal();
        criteria.andUserIdEqualTo(primaryPrincipal.getId());
        if (wxOrderSubmitBo.getCartId() == 0) {
            //如果cartId=0，表示此时cart表中全部fastadd生成的数据都应该已经逻辑删除
            criteria.andCheckedEqualTo(true)
                    .andDeletedEqualTo(false);
        } else {
            //如果cartId!=0，fastadd增加一条数据到cart表，同时该商品加入到页面购物车中
            //如果cartId!=0，表示cartId为cart表主键id，也可根据主键查询得到数据
            criteria.andIdEqualTo(wxOrderSubmitBo.getCartId())
                    .andCheckedEqualTo(true)
                    .andDeletedEqualTo(false);
        }
        List<MarketCart> marketCarts = cartMapper.selectByExample(marketCartExample);

        //根据商品价格、数量、优惠券及运费，得出总价
        //'实付费用， = order_price - integral_price',
        BigDecimal actualPrice = new BigDecimal(0);
        //用户积分减免
        BigDecimal integralPrice = new BigDecimal(0);
        //'订单费用， = goods_price + freight_price - coupon_price',
        BigDecimal orderPrice = new BigDecimal(0);
        //商品总费用
        BigDecimal goodsPrice = new BigDecimal(0);
        //优惠券费用
        BigDecimal couponPrice = new BigDecimal(0);
        //配送费用
        BigDecimal freightPrice = new BigDecimal(0);

        //团购优惠价减免，数据库中运算不包含该项，order表中该字段没有默认值
        BigDecimal grouponPrice = new BigDecimal(0);
        // 先for循环得到商品价格之和
        for (int i = 0; i < marketCarts.size(); i++) {
            MarketCart marketCart = marketCarts.get(i);
            BigDecimal price = marketCart.getPrice();
            Short number = marketCart.getNumber();
            goodsPrice = goodsPrice.add(price.multiply(new BigDecimal(number)));
        }
        //得到couponPrice优惠券减免，根据couponId得到discount值
        if (wxOrderSubmitBo.getCouponId() != -1 && wxOrderSubmitBo.getCouponId() != 0) {
            couponPrice = couponMapper.selectByPrimaryKey(wxOrderSubmitBo.getCouponId()).getDiscount();
        }
        orderPrice = goodsPrice.add(freightPrice).subtract(couponPrice);
        //如果orderPrice小于88元，加10元运费
        if (orderPrice.compareTo(new BigDecimal(88)) == -1) {
            freightPrice = freightPrice.add(new BigDecimal(10));
            orderPrice = goodsPrice.add(freightPrice).subtract(couponPrice);
        }
        actualPrice = orderPrice.subtract(integralPrice);

        //根据addressId获取地址
        MarketAddress marketAddress = addressMapper.selectByPrimaryKey(wxOrderSubmitBo.getAddressId());
        StringBuffer stringBuffer1 = new StringBuffer(marketAddress.getProvince());
        String address = stringBuffer1.append(marketAddress.getCity())
                .append(marketAddress.getCounty())
                .append(marketAddress
                        .getAddressDetail())
                .toString();
        //生成orderSn：年月日+6位随机码
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String format = sdf.format(new Date());
        StringBuffer stringBuffer = new StringBuffer(format);
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            int num = random.nextInt(10);
            stringBuffer.append(num);
        }
        String orderSn = stringBuffer.toString();
        //设置数据
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setUserId(primaryPrincipal.getId());
        marketOrder.setOrderSn(orderSn);
        marketOrder.setOrderStatus((short) 101);
        marketOrder.setAftersaleStatus((short) 0);
        marketOrder.setConsignee(marketAddress.getName());
        marketOrder.setMobile(marketAddress.getTel());
        marketOrder.setAddress(address);
        marketOrder.setMessage("");
        marketOrder.setGoodsPrice(goodsPrice);
        marketOrder.setFreightPrice(freightPrice);
        marketOrder.setCouponPrice(couponPrice);
        marketOrder.setIntegralPrice(integralPrice);
        marketOrder.setOrderPrice(orderPrice);
        marketOrder.setActualPrice(actualPrice);
        marketOrder.setGrouponPrice(grouponPrice);
        marketOrder.setComments((short) marketCarts.size());
        Date addTime = new Date();
        marketOrder.setAddTime(addTime);
        marketOrder.setUpdateTime(addTime);
        marketOrder.setDeleted(false);
        //插入数据
        int affectedRows1 = orderMapper.insertSelective(marketOrder);

        // 插入order_goods表
        for (int i = 0; i < marketCarts.size(); i++) {
            MarketCart marketCart = marketCarts.get(i);
            //赋值
            MarketOrderGoods marketOrderGoods = new MarketOrderGoods();
            //订单insert订单表时，SQL语句设置了主键返回
            marketOrderGoods.setOrderId(marketOrder.getId());
            marketOrderGoods.setGoodsId(marketCart.getGoodsId());
            marketOrderGoods.setGoodsName(marketCart.getGoodsName());
            marketOrderGoods.setGoodsSn(marketCart.getGoodsSn());
            marketOrderGoods.setProductId(marketCart.getProductId());
            marketOrderGoods.setNumber(marketCart.getNumber());
            marketOrderGoods.setPrice(marketCart.getPrice());
            marketOrderGoods.setSpecifications(marketCart.getSpecifications());
            marketOrderGoods.setPicUrl(marketCart.getPicUrl());
            //'订单商品评论，如果是-1，则超期不能评价；如果是0，则可以评价；如果其他值，则是comment表里面的评论ID。
            marketOrderGoods.setComment(0);
            Date addTime1 = new Date();
            marketOrderGoods.setAddTime(addTime1);
            marketOrderGoods.setUpdateTime(addTime1);
            marketOrderGoods.setDeleted(false);
            //插入数据
            orderGoodsMapper.insertSelective(marketOrderGoods);

        }

        if (affectedRows1 == 1) {
            //  需要修改购物车、商品库存、优惠券数量
            //  生成订单后，所使用的优惠券状态改为1（已使用），购物车商品逻辑删除，商品库存减少，
            //将cart表中已下单商品逻辑删除
            for (int i = 0; i < marketCarts.size(); i++) {
                MarketCart marketCart = marketCarts.get(i);
                marketCart.setDeleted(true);
                marketCart.setUpdateTime(new Date());
                cartMapper.updateByPrimaryKeySelective(marketCart);
            }
            //所使用的优惠券状态改为1（已使用）

            if(wxOrderSubmitBo.getUserCouponId()!=-1 && wxOrderSubmitBo.getUserCouponId() != 0) {

                MarketCouponUser marketCouponUser = new MarketCouponUser();
                marketCouponUser.setId(wxOrderSubmitBo.getUserCouponId());
                //'使用状态, 如果是0则未使用；如果是1则已使用；如果是2则已过期；如果是3则已经下架；
                marketCouponUser.setStatus((short) 1);
                marketCouponUser.setUpdateTime(new Date());
                couponUserMapper.updateByPrimaryKeySelective(marketCouponUser);
            }
            //商品库存减少
            //根据market_cart表中“product_id”修改market_goods_product表中数量number
            for (int i = 0; i < marketCarts.size(); i++) {
                MarketCart marketCart = marketCarts.get(i);
                MarketGoodsProduct marketGoodsProduct = new MarketGoodsProduct();
                marketGoodsProduct.setId(marketCart.getProductId());
                //先获取库存，再减(之前已经对库存是否足够做了判断，此处不赘述)
                Integer number = goodsProductMapper.selectByPrimaryKey(marketCart.getProductId()).getNumber();
                marketGoodsProduct.setNumber(number - marketCart.getNumber());
                marketGoodsProduct.setUpdateTime(new Date());
                goodsProductMapper.updateByPrimaryKeySelective(marketGoodsProduct);
            }
        }
        return new WxOrderSubmitPo(0, marketOrder.getId());
    }


    @Override
    public CommonData<WxOrderListVo> list(int showType, BasePageInfo pageInfo) {
        //顺序/逆序
        String orderBy = "add_time";
        //拍寻根据
        String sortBy = "desc";

        PageHelper.startPage(pageInfo.getPage(), pageInfo.getLimit());


        List<WxOrderListVo> wxOrderListVos = new ArrayList<>();

        if (showType == 0) {
            //显示所有订单
            MarketOrderExample orderExample = new MarketOrderExample();
            orderExample.setOrderByClause(orderBy+" "+sortBy);
            MarketOrderExample.Criteria criteria = orderExample.createCriteria();
            criteria.andDeletedEqualTo(false);



            //数据库po,转化vo
            List<MarketOrder> orderList = orderMapper.selectByExample(orderExample);


            for (MarketOrder order : orderList) {
                //查到的数据放入orderlist
                WxOrderListVo wxOrderListVo = new WxOrderListVo();
                wxOrderListVo.setId(order.getId());
                wxOrderListVo.setOrderSn(order.getOrderSn());
                wxOrderListVo.setOrderStatusText(order.getOrderStatus());
                wxOrderListVo.setAftersaleStatus(order.getAftersaleStatus());
                wxOrderListVo.setActualPrice(order.getActualPrice());
                wxOrderListVo.setHandleOption(OptionStatus.chooseStatus(order.getOrderStatus()));


                //写入list
                wxOrderListVos.add(wxOrderListVo);
            }



            for (WxOrderListVo wxOrderListVo : wxOrderListVos) {

                //goodsListvo
                List<WxOrderGoodsVo> orderGoodsVoList = new ArrayList<>();

                Integer orderId = wxOrderListVo.getId();

                MarketOrderGoodsExample orderGoodsExample = new MarketOrderGoodsExample();
                MarketOrderGoodsExample.Criteria criteria1 = orderGoodsExample.createCriteria();

                criteria1.andOrderIdEqualTo(orderId)
                        .andDeletedEqualTo(false);

                List<MarketOrderGoods> orderGoodsList = orderGoodsMapper.selectByExample(orderGoodsExample);

                //查到的goodsList封装进orderGoodsVoList
                for (MarketOrderGoods marketOrderGoods : orderGoodsList) {
                    WxOrderGoodsVo orderGoodsVo = new WxOrderGoodsVo(marketOrderGoods.getOrderId()
                            , marketOrderGoods.getGoodsName(), marketOrderGoods.getNumber()
                            , marketOrderGoods.getPrice(), marketOrderGoods.getSpecifications()
                            , marketOrderGoods.getPicUrl());

                    orderGoodsVoList.add(orderGoodsVo);

                }

                wxOrderListVo.setGoodsList(orderGoodsVoList);

            }


        }

        if (showType == 1) {
            //待付款
            MarketOrderExample orderExample = new MarketOrderExample();
            MarketOrderExample.Criteria criteria = orderExample.createCriteria();
            criteria.andDeletedEqualTo(false)
            .andOrderStatusEqualTo(new Short("101"));

            //数据库po,转化vo
            List<MarketOrder> orderList = orderMapper.selectByExample(orderExample);


            for (MarketOrder order : orderList) {
                //查到的数据放入orderlist
                WxOrderListVo wxOrderListVo = new WxOrderListVo();
                wxOrderListVo.setId(order.getId());
                wxOrderListVo.setOrderSn(order.getOrderSn());
                wxOrderListVo.setOrderStatusText(order.getOrderStatus());
                wxOrderListVo.setAftersaleStatus(order.getAftersaleStatus());
                wxOrderListVo.setActualPrice(order.getActualPrice());
                wxOrderListVo.setHandleOption(OptionStatus.chooseStatus(order.getOrderStatus()));


                //写入list
                wxOrderListVos.add(wxOrderListVo);
            }



            for (WxOrderListVo wxOrderListVo : wxOrderListVos) {

                //goodsListvo
                List<WxOrderGoodsVo> orderGoodsVoList = new ArrayList<>();

                Integer orderId = wxOrderListVo.getId();

                MarketOrderGoodsExample orderGoodsExample = new MarketOrderGoodsExample();
                MarketOrderGoodsExample.Criteria criteria1 = orderGoodsExample.createCriteria();

                criteria1.andOrderIdEqualTo(orderId)
                        .andDeletedEqualTo(false);

                List<MarketOrderGoods> orderGoodsList = orderGoodsMapper.selectByExample(orderGoodsExample);

                //查到的goodsList封装进orderGoodsVoList
                for (MarketOrderGoods marketOrderGoods : orderGoodsList) {
                    WxOrderGoodsVo orderGoodsVo = new WxOrderGoodsVo(marketOrderGoods.getOrderId()
                            , marketOrderGoods.getGoodsName(), marketOrderGoods.getNumber()
                            , marketOrderGoods.getPrice(), marketOrderGoods.getSpecifications()
                            , marketOrderGoods.getPicUrl());

                    orderGoodsVoList.add(orderGoodsVo);

                }

                wxOrderListVo.setGoodsList(orderGoodsVoList);

            }

        }

        if (showType == 2) {
            //待发货
            MarketOrderExample orderExample = new MarketOrderExample();
            MarketOrderExample.Criteria criteria = orderExample.createCriteria();
            criteria.andDeletedEqualTo(false)
                    .andOrderStatusEqualTo(new Short("201"));

            //数据库po,转化vo
            List<MarketOrder> orderList = orderMapper.selectByExample(orderExample);


            for (MarketOrder order : orderList) {
                //查到的数据放入orderlist
                WxOrderListVo wxOrderListVo = new WxOrderListVo();
                wxOrderListVo.setId(order.getId());
                wxOrderListVo.setOrderSn(order.getOrderSn());
                wxOrderListVo.setOrderStatusText(order.getOrderStatus());
                wxOrderListVo.setAftersaleStatus(order.getAftersaleStatus());
                wxOrderListVo.setActualPrice(order.getActualPrice());
                wxOrderListVo.setHandleOption(OptionStatus.chooseStatus(order.getOrderStatus()));


                //写入list
                wxOrderListVos.add(wxOrderListVo);
            }



            for (WxOrderListVo wxOrderListVo : wxOrderListVos) {

                //goodsListvo
                List<WxOrderGoodsVo> orderGoodsVoList = new ArrayList<>();

                Integer orderId = wxOrderListVo.getId();

                MarketOrderGoodsExample orderGoodsExample = new MarketOrderGoodsExample();
                MarketOrderGoodsExample.Criteria criteria1 = orderGoodsExample.createCriteria();

                criteria1.andOrderIdEqualTo(orderId)
                        .andDeletedEqualTo(false);

                List<MarketOrderGoods> orderGoodsList = orderGoodsMapper.selectByExample(orderGoodsExample);

                //查到的goodsList封装进orderGoodsVoList
                for (MarketOrderGoods marketOrderGoods : orderGoodsList) {
                    WxOrderGoodsVo orderGoodsVo = new WxOrderGoodsVo(marketOrderGoods.getOrderId()
                            , marketOrderGoods.getGoodsName(), marketOrderGoods.getNumber()
                            , marketOrderGoods.getPrice(), marketOrderGoods.getSpecifications()
                            , marketOrderGoods.getPicUrl());

                    orderGoodsVoList.add(orderGoodsVo);

                }

                wxOrderListVo.setGoodsList(orderGoodsVoList);

            }

        }

        if (showType == 3) {
            //待收货
            MarketOrderExample orderExample = new MarketOrderExample();
            MarketOrderExample.Criteria criteria = orderExample.createCriteria();
            criteria.andDeletedEqualTo(false)
                    .andOrderStatusEqualTo(new Short("301"));

            //数据库po,转化vo
            List<MarketOrder> orderList = orderMapper.selectByExample(orderExample);


            for (MarketOrder order : orderList) {
                //查到的数据放入orderlist
                WxOrderListVo wxOrderListVo = new WxOrderListVo();
                wxOrderListVo.setId(order.getId());
                wxOrderListVo.setOrderSn(order.getOrderSn());
                wxOrderListVo.setOrderStatusText(order.getOrderStatus());
                wxOrderListVo.setAftersaleStatus(order.getAftersaleStatus());
                wxOrderListVo.setActualPrice(order.getActualPrice());
                wxOrderListVo.setHandleOption(OptionStatus.chooseStatus(order.getOrderStatus()));


                //写入list
                wxOrderListVos.add(wxOrderListVo);
            }



            for (WxOrderListVo wxOrderListVo : wxOrderListVos) {

                //goodsListvo
                List<WxOrderGoodsVo> orderGoodsVoList = new ArrayList<>();

                Integer orderId = wxOrderListVo.getId();

                MarketOrderGoodsExample orderGoodsExample = new MarketOrderGoodsExample();
                MarketOrderGoodsExample.Criteria criteria1 = orderGoodsExample.createCriteria();

                criteria1.andOrderIdEqualTo(orderId)
                        .andDeletedEqualTo(false);

                List<MarketOrderGoods> orderGoodsList = orderGoodsMapper.selectByExample(orderGoodsExample);

                //查到的goodsList封装进orderGoodsVoList
                for (MarketOrderGoods marketOrderGoods : orderGoodsList) {
                    WxOrderGoodsVo orderGoodsVo = new WxOrderGoodsVo(marketOrderGoods.getOrderId()
                            , marketOrderGoods.getGoodsName(), marketOrderGoods.getNumber()
                            , marketOrderGoods.getPrice(), marketOrderGoods.getSpecifications()
                            , marketOrderGoods.getPicUrl());

                    orderGoodsVoList.add(orderGoodsVo);

                }

                wxOrderListVo.setGoodsList(orderGoodsVoList);

            }

        }

        if (showType == 4) {
            //待评价
            MarketOrderExample orderExample = new MarketOrderExample();
            orderBy = "ship_time";
            orderExample.setOrderByClause(orderBy+" "+sortBy);
            MarketOrderExample.Criteria criteria = orderExample.createCriteria();
            criteria.andDeletedEqualTo(false)
                    .andOrderStatusEqualTo(new Short("401"));

            //数据库po,转化vo
            List<MarketOrder> orderList = orderMapper.selectByExample(orderExample);


            for (MarketOrder order : orderList) {
                //查到的数据放入orderlist
                WxOrderListVo wxOrderListVo = new WxOrderListVo();
                wxOrderListVo.setId(order.getId());
                wxOrderListVo.setOrderSn(order.getOrderSn());
                wxOrderListVo.setOrderStatusText(order.getOrderStatus());
                wxOrderListVo.setAftersaleStatus(order.getAftersaleStatus());
                wxOrderListVo.setActualPrice(order.getActualPrice());
                wxOrderListVo.setHandleOption(OptionStatus.chooseStatus(order.getOrderStatus()));


                //写入list
                wxOrderListVos.add(wxOrderListVo);
            }



            for (WxOrderListVo wxOrderListVo : wxOrderListVos) {

                //goodsListvo
                List<WxOrderGoodsVo> orderGoodsVoList = new ArrayList<>();

                Integer orderId = wxOrderListVo.getId();

                MarketOrderGoodsExample orderGoodsExample = new MarketOrderGoodsExample();
                MarketOrderGoodsExample.Criteria criteria1 = orderGoodsExample.createCriteria();

                criteria1.andOrderIdEqualTo(orderId)
                        .andDeletedEqualTo(false);

                List<MarketOrderGoods> orderGoodsList = orderGoodsMapper.selectByExample(orderGoodsExample);

                //查到的goodsList封装进orderGoodsVoList
                for (MarketOrderGoods marketOrderGoods : orderGoodsList) {
                    WxOrderGoodsVo orderGoodsVo = new WxOrderGoodsVo(marketOrderGoods.getOrderId()
                            , marketOrderGoods.getGoodsName(), marketOrderGoods.getNumber()
                            , marketOrderGoods.getPrice(), marketOrderGoods.getSpecifications()
                            , marketOrderGoods.getPicUrl());

                    orderGoodsVoList.add(orderGoodsVo);

                }

                wxOrderListVo.setGoodsList(orderGoodsVoList);

            }

        }
        PageInfo<WxOrderListVo> info = new PageInfo<>(wxOrderListVos);


        return CommonData.data(info);
}

    @Override
    public WxOrderDetailVo detail(int orderId) {

        //返回对象
        WxOrderDetailVo wxOrderDetailVo = new WxOrderDetailVo();

        MarketOrderExample orderExample = new MarketOrderExample();
        MarketOrderExample.Criteria criteria = orderExample.createCriteria();
        criteria.andIdEqualTo(orderId);

        //查orderInfo
        MarketOrder marketOrder = orderMapper.selectByPrimaryKey(orderId);

        //封装orderInfo 不包括orderStatusText handleOption
        WxOrderDetailOrderInfoVo orderDetailOrderInfoVo = new WxOrderDetailOrderInfoVo(marketOrder.getId(),
                marketOrder.getOrderSn(),marketOrder.getAftersaleStatus(),marketOrder.getConsignee()
        ,marketOrder.getMobile(),marketOrder.getAddress(),marketOrder.getMessage(),marketOrder.getGoodsPrice()
        ,marketOrder.getFreightPrice(),marketOrder.getCouponPrice(),marketOrder.getActualPrice(),marketOrder.getAddTime(),
                marketOrder.getShipChannel(),marketOrder.getShipSn());

        //set方法中转换字符串
        orderDetailOrderInfoVo.setOrderStatusText(marketOrder.getOrderStatus());
        //工具类根据状态码处理handleOption
        orderDetailOrderInfoVo.setHandleOption(OptionStatus.chooseStatus(marketOrder.getOrderStatus()));
        //工具类处理快递公司名
        if(marketOrder.getShipChannel()!= null) {
            orderDetailOrderInfoVo.setExpName(ExpressCompany.expressName(marketOrder.getShipChannel()));
        }
        //orderInfo放进vo
        wxOrderDetailVo.setOrderInfo(orderDetailOrderInfoVo);


        //根据orderId查orderGoods
        MarketOrderGoodsExample orderGoodsExample = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria criteria1 = orderGoodsExample.createCriteria();
        criteria1.andOrderIdEqualTo(orderId);

        List<MarketOrderGoods> marketOrderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);

        wxOrderDetailVo.setOrderGoods(marketOrderGoods);


        return wxOrderDetailVo;
    }

    @Override
    public void cancel(WxOrderCancelBo wxOrderCancelBo) {
        //取消订单把状态码从101 -> 102
        Date date = new Date(System.currentTimeMillis());

        int orderId = wxOrderCancelBo.getOrderId();
        MarketOrderExample orderExample = new MarketOrderExample();
        MarketOrderExample.Criteria criteria = orderExample.createCriteria();
        criteria.andIdEqualTo(orderId);
        MarketOrder marketOrder = orderMapper.selectByPrimaryKey(orderId);
        marketOrder.setOrderStatus(new Short("102"));
        marketOrder.setUpdateTime(date);
        marketOrder.setEndTime(date);


        orderMapper.updateByExampleSelective(marketOrder,orderExample);

    }

    @Override
    public void refund(WxOrderCancelBo wxOrderRefundBo) {
        //申请退款把201->202
        Date date = new Date(System.currentTimeMillis());
        int orderId = wxOrderRefundBo.getOrderId();
        MarketOrderExample orderExample = new MarketOrderExample();
        MarketOrderExample.Criteria criteria = orderExample.createCriteria();
        criteria.andIdEqualTo(orderId);
        MarketOrder marketOrder = orderMapper.selectByPrimaryKey(orderId);
        marketOrder.setOrderStatus(new Short("202"));
        marketOrder.setUpdateTime(date);

        orderMapper.updateByExampleSelective(marketOrder,orderExample);

    }

    @Override
    public void confirm(WxOrderCancelBo wxOrderConfirmBo) {
        //确认收货301->401
        Date date = new Date(System.currentTimeMillis());
        int orderId = wxOrderConfirmBo.getOrderId();
        MarketOrderExample orderExample = new MarketOrderExample();
        MarketOrderExample.Criteria criteria = orderExample.createCriteria();
        criteria.andIdEqualTo(orderId);
        MarketOrder marketOrder = orderMapper.selectByPrimaryKey(orderId);
        marketOrder.setOrderStatus(new Short("401"));
        marketOrder.setUpdateTime(date);
        orderMapper.updateByExampleSelective(marketOrder,orderExample);

    }

    /**
     * 商品评价前的goods信息回显
     * @author Tezel
     * @date 2022/07/20
     */

    @Override
    public MarketOrderGoods goods(Integer orderId, Integer goodsId) {
        MarketOrderGoodsExample orderGoodsExample = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria criteria = orderGoodsExample.createCriteria();
        criteria.andOrderIdEqualTo(orderId)
                .andGoodsIdEqualTo(goodsId);

        List<MarketOrderGoods> marketOrderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);

        MarketOrderGoods data = null;
        if (marketOrderGoods!=null) {
            data = marketOrderGoods.get(0);
        }


        return data;
    }

    @Override
    public void comment( WxOrderCommentBo wxOrderCommitBo) {

        //新增的评论
        MarketComment marketComment = new MarketComment();

        //参数信息放入comment
        BeanUtils.copyProperties(wxOrderCommitBo, marketComment);

        Date date = new Date(System.currentTimeMillis());
        marketComment.setAddTime(date);
        marketComment.setUpdateTime(date);
        marketComment.setDeleted(false);
        marketComment.setType(new Byte("0"));

        //TODO 用户id获取
        marketComment.setUserId(1);

        Integer orderGoodsId = wxOrderCommitBo.getOrderGoodsId();

        //ordergoods表主键id 找到 goodsId orderId
        MarketOrderGoods orderGoods = orderGoodsMapper.selectByPrimaryKey(orderGoodsId);

        //封装comment的 value_id
        marketComment.setValueId(orderGoods.getGoodsId());

        //插入comment一个数据 得到主键id  更改ordergoods表中的comment状态  维护commentId

        commentMapper.insertSelective(marketComment);

        //主键自增的id
        Integer commentId = marketComment.getId();

        MarketOrderGoodsExample orderGoodsExample = new MarketOrderGoodsExample();

        MarketOrderGoodsExample.Criteria criteria = orderGoodsExample.createCriteria();

        criteria.andIdEqualTo(orderGoodsId);

        //用于更新ordergoods表中的comment的
        MarketOrderGoods comment = new MarketOrderGoods();

        //评论表中的新增的评论id
        comment.setComment(commentId);

        orderGoodsMapper.updateByExampleSelective(comment,orderGoodsExample);

        // todo order表comments数量维护
        Integer orderId = orderGoods.getOrderId();

        //评论后待评论comments减少  todo 用于计算user/index的数量

        MarketOrder marketOrder = orderMapper.selectByPrimaryKey(orderId);

        Short commentsCount = marketOrder.getComments();

        Short updateCount = new Short((short) (commentsCount.intValue()-1));

        //更新order表中的comments
        MarketOrder marketOrder1 = new MarketOrder();
        marketOrder1.setComments(updateCount);

        MarketOrderExample orderExample = new MarketOrderExample();

        MarketOrderExample.Criteria criteria1 = orderExample.createCriteria();

        criteria1.andIdEqualTo(orderId);

        orderMapper.updateByExampleSelective(marketOrder1,orderExample);



    }

    @Override
    public void prepay(Integer id) {
        //生成payId：年月日+6位随机码
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String format = sdf.format(new Date());
        StringBuffer stringBuffer = new StringBuffer(format);
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            int num = random.nextInt(10);
            stringBuffer.append(num);
        }
        String payId = stringBuffer.toString();
        //赋值
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setId(id);
        marketOrder.setPayId(payId);
        marketOrder.setOrderStatus((short)201);
        Date payTime = new Date();
        marketOrder.setPayTime(payTime);
        marketOrder.setUpdateTime(payTime);
        //update
        orderMapper.updateByPrimaryKeySelective(marketOrder);
    }
}
